package org.angelica.pay;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfig;
import com.github.wxpay.sdk.WXPayConstants;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * @author aizhimin
 */
@Configuration
@ConfigurationProperties(prefix = "pay.wxpay")
@Slf4j
@Data
public class WxpayConfig implements WXPayConfig {

    /** 公众账号ID */
    private String appID;

    /** 商户号 */
    private String mchID;

    /** API 密钥 */
    private String key;

    /** API 沙箱环境密钥 */
    private String sandboxKey;

    /** API证书绝对路径 */
    private String certPath;

    /** 支付通知地址 */
    private String notifyPayUrl;

    /** 退款异步通知地址 */
    private String notifyRefundUrl;

    /** 是否使用沙盒环境 */
    private Boolean useSandbox;

    /** HTTP(S) 连接超时时间，单位毫秒 */
    private int httpConnectTimeoutMs = 8000;

    /** HTTP(S) 读数据超时时间，单位毫秒 */
    private int httpReadTimeoutMs = 10000;

    @Override
    public String getKey() {
        if (useSandbox) {
            return sandboxKey;
        }
        return key;
    }

    @Override
    public InputStream getCertStream() {
        File certFile = new File(certPath);
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(certFile);
        } catch (FileNotFoundException e) {
            log.error("cert file not found, path={}, exception is:{}", certPath, e);
        }
        return inputStream;
    }

    @Bean
    public WXPay wxPay() {
        return new WXPay(this, WXPayConstants.SignType.MD5, getUseSandbox() );
    }
}
